<?php
namespace Icsoc\ReportForRoleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\VarDumper\VarDumper;
use Icsoc\ExportLib\Col;

/**
 * 数据报表
 *
 * Class CommonController
 * @package Icsoc\ReportForRoleBundle\Controller
 */
class CommonController extends Controller
{
    /**
     * 公共渲染
     *
     * @param String $type
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction($type)
    {
        $data = $this->getTypeData($type);
        $listUrl = 'icsoc_report_system_home';
        switch ($type) {
            case 'system':
                $listUrl = 'icsoc_report_system_list';
                break;
            case 'queue':
                $listUrl = 'icsoc_report_queue_list';
                break;
            case 'group':
                $listUrl = 'icsoc_report_group_list';
                break;
            case 'agent':
                $listUrl = 'icsoc_report_agent_list';
                break;
        }
        $isSpecial = $this->container->get("icsoc_core.common.class")->getIsAdmin();

        return $this->render('IcsocReportForRoleBundle:Data:index.html.twig', array(
            'type' => $type,
            'data' => $data,
            'date' => $this->container->get("icsoc_report_for_role.common")->getDate(),
            'listUrl' => $listUrl,
            'isSpecial' => $isSpecial
        ));
    }

    /**
     * 呼叫中心整体话务报表
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function systemAction()
    {
        return $this->forward("IcsocReportForRoleBundle:Common:index", array('type' => 'system'));
    }

    /**
     * 技能组报表
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function queueAction()
    {
        return $this->forward("IcsocReportForRoleBundle:Common:index", array('type' => 'queue'));
    }

    /**
     * 坐席工作表现报表
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function agentAction()
    {
        return $this->forward("IcsocReportForRoleBundle:Common:index", array('type' => 'agent'));
    }

    /**
     * 业务组报表
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function groupAction()
    {
        return $this->forward("IcsocReportForRoleBundle:Common:index", array('type' => 'group'));
    }

    /**
     * 展示列表
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listAction(Request $request)
    {
        $data = $request->get('data', '');
        $originParam = $request->get('data', '');
        $data = html_entity_decode(urldecode($data));
        $data = json_decode($data, true);
        $param['report_type'] = empty($data['report_type']) ? '' : $data['report_type'];
        $param['start_date'] = empty($data['start_date']) ? '' : $data['start_date'];
        $param['end_date'] = empty($data['end_date']) ? '' : $data['end_date'];
        $param['data_id'] = empty($data['data_id']) ? '' : $data['data_id'];
        $param['type'] = empty($data['type']) ? '' : $data['type'];
        $param['report_show_type'] = empty($data['report_show_type']) ? '' : $data['report_show_type'];

        $dataUrl = 'icsoc_report_system_data';
        switch ($param['type']) {
            case 'system':
                $dataUrl = 'icsoc_report_system_data';
                break;
            case 'queue':
                $dataUrl = 'icsoc_report_queue_data';
                break;
            case 'group':
                $dataUrl = 'icsoc_report_group_data';
                break;
            case 'agent':
                $dataUrl = 'icsoc_report_agent_data';
                break;
        }

        $roleId = $request->get('role_id', '');
        /** 获取角色信息*/
        $vccId = $this->getUser()->getVccId();
        $roleInfo = $this->getRoleInfo($vccId);
        if ($roleInfo['isAdmin'] == true) {
            if (empty($roleId)) {
                $roleIds = array_keys($roleInfo['roles']);
                $selected = $roleIds[0];
            } else {
                $selected = $roleId;
            }
            $roleShow = true;
        } else {
            $roleShow = false;
            $roleId = array_keys($roleInfo['roles']);
            $selected = $roleId[0];
        }

        $options = array(
            'role_id' => array(
                'text' => 'The role',
                'options' => $roleInfo['roles'],
                'selected' => $selected,
            ),
        );
        $param['roleId'] = $selected;

        $rst = $this->get('icsoc_report_for_role.model.report')->getTitleReport(
            array('report_name' => $param['type'], 'report_type' => $param['report_type'], 'roleId' => $selected)
        );
        $title = array();
        if (isset($rst['code']) && $rst['code'] == 200) {
            $title = $rst['data'];
        }
        $item['title'] = $title;
        $item['caption'] = ucfirst($param['type']).' Caption 【%start_date% ~ %end_date%】';
        $item['start_date'] = empty($param['start_date']) ? '' : $param['start_date'];
        $item['end_date'] = empty($param['end_date']) ? '' : $param['end_date'];

        $item['report_type'] = $this->get("translator")->trans($param['report_type']);
        $backUrl = $this->generateUrl(sprintf("icsoc_report_%s_home", $param['type']));
        return $this->render('IcsocReportForRoleBundle:Data:list.html.twig', array(
            'item' => $item,
            'param' => json_encode($param),
            'options' => $options,
            'action' => 'icsoc_report_for_role_list',
            'originParam' => $originParam,
            'roleShow' => $roleShow,
            'dataUrl' => $dataUrl,
            'backUrl' => $backUrl,
        ));
    }

    /**
     * 获取列表数据
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function dataAction(Request $request)
    {
        $data = $request->get('param', '');
        $data = html_entity_decode(urldecode($data));
        $data = json_decode($data, true);
        $roleId = $request->get('roleId', '');
        if (empty($roleId)) {
            $roleId = $data['roleId'];
        }
        $vccId = $this->getUser()->getVccId();
        $startDate = empty($data['start_date']) ? '' : $data['start_date'];
        $endDate = empty($data['end_date']) ? '' : $data['end_date'];
        $dataId = empty($data['data_id']) ? '' : $data['data_id'];
        $reportShowType = empty($data['report_show_type']) ? '' : $data['report_show_type'];
        if (in_array($data['type'], array('agent', 'queue', 'group'))) {
            $authority = $this->getTypeData($data['type']);
            $allDataIds = $authority['dataIds'];
            $dataId = empty($data['data_id']) ? $allDataIds : $data['data_id'];
        }
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sidx = $request->get('sidx', '1');
        $orders = $this->getSortField($sidx, $data['report_type'], $reportShowType);
        $sidx = $orders['sidx'];
        $order = !empty($request->get('sord'))? $request->get('sord') : $orders['order'];
        $export = $request->get('export', '');

        /** @var  $param (数据参数) */
        $param = array(
            'export' => $export,
            'pagination' => array(
                'rows' => $rows,
                'page' => $page,
            ),
            'sort' => array(
                'order' => $order,
                'field' => $sidx,
            ),
            'filter' => array(
                'start_date' => $startDate,
                'end_date' => $endDate,
                'data_id' => $dataId,
            ),
        );
        $param = array(
            'vcc_code' => $this->getUser()->getVccCode(),
            'info' => json_encode($param),
            'rep_type' => $data['report_type'],
            'type' => $data['type'],
            'roleId' => $roleId,
            'report_show_type' => $reportShowType,
        );
        if (empty($export)) {
            $result = $this->get('icsoc_report_for_role.model.report')->getData($param);
            if ($result['code'] == 200) {
                $result = array(
                    'total' => $result['total'],
                    'page' => $result['page'],
                    'records' => $result['records'],
                    'rows' => $result['rows'],
                    'userdata' => $result['footer'],
                );
            } else {
                $result = array(
                    'total' => 0,
                    'page' => 1,
                    'records' => 0,
                    'rows' => array(),
                    'code' => $result['code'],
                    'message' => $result['message'],
                    'sql' => $result['sql'],
                );
            }
        } else {
            set_time_limit(180);
            $result = $this->get('icsoc_report_for_role.model.report')->getExportFile($param);

            return $result;
        }

        return new JsonResponse($result);
    }

    /**
     * 根据type获取Data
     *
     * @param $type
     * @return array
     */
    private function getTypeData($type)
    {
        $data = array('is_show'=>1);
        switch ($type) {
            case 'system':
                $data['is_show'] = 0;
                break;
            case 'queue':
                $data['text'] = $this->get("translator")->trans('Queues');
                $data['please'] = $this->get("translator")->trans('Please Select Queues');
                $row = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($this->getUser()->getVccId(), true, true);
                $data['data'] = $row;
                $data['dataIds'] = implode(',', array_keys($row));
                break;
            case 'group':
                $em = $this->getDoctrine()->getManager();
                $vccId = $this->getUser()->getVccId();
                $row = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
                $data['text'] = $this->get("translator")->trans('Groups');
                $data['please'] = $this->get("translator")->trans('Please Select Groups');
                $data['data'] = $row;
                $data['dataIds'] = implode(',', array_keys($row));
                break;
            case 'agent':
                $row = $this->get('icsoc_data.model.agent')->getAgentNameKeyedByIdArray($this->getUser()->getVccId(), true);
                $data['text'] = $this->get("translator")->trans('Agents');
                $data['please'] = $this->get("translator")->trans('Please Select Agents');
                $data['data'] = $row;
                $data['dataIds'] = implode(',', array_keys($row));
                break;
        }

        return $data;
    }

    /**
     * 获取日期的排序字段
     *
     * @param $sidx
     * @param $type
     * @return array|string
     */
    private function getSortField($sidx, $type, $reportShowType)
    {
        $order = '';
        if ($sidx == 'date') {
            switch ($type) {
                case 'month':
                    $sidx = 'start_date';
                    $order = 'desc';
                    break;
                case 'day':
                    $sidx = 'nowdate';
                    $order = 'desc';
                    break;
                case 'hour':
                    if (!empty($reportShowType) && $reportShowType == 2) {
                        $sidx = 'time_stamp';
                        $order = 'desc';
                    } else {
                        $sidx = array('start_date', 'time_stamp');
                        $order = 'asc';
                    }
                    break;
                case 'halfhour':
                    if (!empty($reportShowType) && $reportShowType == 2) {
                        $sidx = 'time_stamp';
                        $order = 'desc';
                    } else {
                        $sidx = array('start_date', 'time_stamp');
                        $order = 'asc';
                    }
                    break;
            }
        }

        return array('sidx' => $sidx, 'order' => $order);
    }


    /**
     * 获取角色信息
     *
     * @param $vccId
     * @return array  array('roleId' => 'roleName')
     */
    public function getRoleInfo($vccId)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $loginType = $user->getLoginType();
        $roleGrade = $user->getRoleGrade();

        //loginType=2时，是普通用户登录，此时只有一个角色
        if ($loginType == 2) {
            $userRole = $user->getUserRole();
            $roleWhere = "AND r.roleGrade = :roleGrade";
            $roles = $em->getRepository("IcsocSecurityBundle:CcRoles")
                ->getRolesName("r.vccId = :vccId $roleWhere", array('vccId' => $vccId, 'roleGrade' => $roleGrade));
            $roleName = $roles[$userRole];
            $res = array('isAdmin' => false, 'roles' => array($userRole => $roleName));
        } else {
            $roleWhere = $roleGrade < 3 ? "AND r.roleGrade > :roleGrade" : "AND r.roleGrade = :roleGrade";
            $roles = $em->getRepository("IcsocSecurityBundle:CcRoles")
                ->getRolesName("r.vccId = :vccId $roleWhere", array('vccId' => $vccId, 'roleGrade' => $roleGrade));
            $res = array('isAdmin' => true, 'roles' =>$roles);
        }

        return $res;
    }
}
